// wsUtils.js
import API from '@/js/api';
import { generateTimestampBasedID } from './baseUtils';

class WebSocketClient {
    constructor() {
        this.url = 'ws://localhost:3000';
        this.uuid = generateTimestampBasedID();
        this.socket = null;

        // 重连相关属性
        this.isReconnecting = false;
        this.reconnectAttempts = 0; // 当前重连尝试次数
        this.maxReconnectAttempts = 20; // 最大重连尝试次数
        this.reconnectDelay = 3000; // 初始重连延迟时间（毫秒）

        // 定义回调函数
        this.callbacks = [];
    }

    init() {
        this.connect();
    }

    connect() {
        try {
            let _this = this;
            this.socket = new WebSocket(`${this.url}?uuid=${this.uuid}`);

            // 连接建立之后的回调
            this.socket.addEventListener('open', (event) => {
                console.log('WebSocket connection opened');
                this.reconnectAttempts = 0; // 重置重连尝试次数
            });

            // 收到消息时的回调
            this.socket.addEventListener('message', function (event) {
                // console.log('Message from server: ', event.data);
                for (let i = 0; i < _this.callbacks.length; i++) {
                    let callback = _this.callbacks[i];
                    callback(event.data);
                }
            });

            // WebSocket 关闭时的回调
            this.socket.addEventListener('close', (event) => {
                console.log('WebSocket connection closed');
                if (!this.isReconnecting) {
                    this.handleReconnect();
                }
            });

            // WebSocket 出现错误时的回调
            this.socket.addEventListener('error', (event) => {
                console.error('WebSocket error: ', event);
                if (!this.isReconnecting) {
                    this.handleReconnect();
                }
            });
        } catch (error) {
            // console.error('WebSocket connection error:', error);
        }
    }

    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            console.warn(`Reconnect attempt #${this.reconnectAttempts}`);
            this.isReconnecting = true;
            this.reconnectAttempts++;

            setTimeout(async () => {
                this.isReconnecting = false;
                if (await this.checkWebSocketServer()) {
                    this.connect();
                } else {
                    this.handleReconnect();
                }
            }, this.reconnectDelay);
        }
    }

    // 这里可以实现对本地 WebSocket 服务器存在性的检测
    async checkWebSocketServer() {
        try {
            let result = await API.invoke('Ping', {});
            if (result.code == 0) {
                return true;
            } else {
                return false;
            }
        } catch (error) {
            return false;
        }
    }

    // 注册回调函数
    addCallback(callback) {
        this.callbacks.push(callback);
    }

    // 移除回调函数
    removeCallback(callback) {
        let index = this.callbacks.indexOf(callback);
        if (index > -1) {
            this.callbacks.splice(index, 1);
        }
    }

    // 清除所有回调函数
    clearCallbacks() {
        this.callbacks = [];
    }
}

export default WebSocketClient;
